<?php

function _ctlMenu($name, $attribs)
{
	$cacheId = 'WebControl.DynamicMenu.' . $name;
	if (defined('DEPLOY_MODE') && DEPLOY_MODE) {
	    $lifetime = 900;
	} else {
	    $lifetime = 0;
	}
	$rowset = FLEA::getCache($cacheId, $lifetime);
	if (!$rowset) {
		$tableSysMenu =& FLEA::getSingleton('Table_Menu');
		/* @var $tableSysMenu Table_SysMenu */
		$rowset = $tableSysMenu->findAll(null, 'parent_id ASC, order_pos ASC');
		FLEA::writeCache($cacheId, $rowset);
	}

	/**
	 * 首先用 RBAC 过滤不能访问的菜单项
	 */
	$dispatcher =& FLEA::getSingleton(FLEA::getAppInf('dispatcher'));
	/* @var $dispatcher FLEA_Dispatcher_Auth */
	foreach ($rowset as $offset => $row) {
		if ($row['controller'] == '') { continue; }
		if (!$dispatcher->check($row['controller'], $row['action'])) {
			unset($rowset[$offset]);
		} else {
			$args = array();
			parse_str($row['args'], $args);
			$rowset[$offset]['url'] = url($row['controller'], $row['action'], $args);
		}
	}


	/**
	 * 缓存菜单
	 */
	$mainMenu =& new Helper_Menu($rowset);

	$output = "";
	$output .= $mainMenu->returnJsArray(true);

	echo <<<EOT

<div class="dtree">

<script language="javascript" type="text/javascript" src="script/dtree.js"></script>
<link rel="StyleSheet" href="script/dtree.css" type="text/css">
<p><a href="javascript: d.openAll();">全部展开</a> | <a href="javascript: d.closeAll();">全部折叠</a></p>
<script language="javascript" type="text/javascript">
		d = new dTree('d');
		d.add(0,-1,'管理首页','?controller=admin_login&action=cpindex');
		{$output}
		document.write(d);
</script>

</div>
EOT;

}


class Helper_Menu
{
	var $_menu = array();

	var $_refs = array();

	function Helper_Menu($menu = null)
	{
		$this->_menu = $menu;
	}

	function returnJsArray()
	{
	    $out = '';
		foreach ($this->_menu as $value) {
	    	$out .= "d.add({$value['menu_id']},{$value['parent_id']},'{$value['title']}','{$value['url']}');\n";
	    }
		return $out;
	}


}

?>